<?php
/*
 * @Description  : 类别管理
 * @Author       : https://github.com/skyselang
 * @Date         : 2020-05-05
 * @LastEditTime : 2020-12-25
 */

namespace app\admin\service;

use app\common\cache\CateGoryCache;
use think\facade\Db;
use Exception;

class CateGoryService
{
    const TABLE = 'category';
    /**
     * 查询条件
     *
     * @param array   $data   参数
     * 
     * @return array 
     */
    private static function map(array $data){
        $map = [];
        if($data['category_type']){
            $map['category_type'] = $data['category_type'];
        }
        if($data['category_name']){
            $map['category_name'] = $data['category_name'];
        }
        if($data['category_status']){
            $map['category_status'] = $data['category_status'];
        }
        return $map;
    }

    /**
     * 类别列表
     *
     * @param array   $param   参数
     * @param integer $page    页数
     * @param integer $limit   数量
     * @param string  $field   字段
     * @param boole  $getAll   是否获取所有字段和数据
     * 
     * @return array 
     */
    public static function findList($param = [], $pp = 1, $num = 10, $field = '',$getAll = false)
    {
        //查询条件
        $map = self::map($param);
        $order = ['category_sort' => 'desc', 'category_id' => 'desc'];
        if($getAll){
            return [
                'list' => Db::name(self::TABLE)->where($map)->order($order)->field($field)->column("*","category_id")
            ];
        }
        $count = Db::name(self::TABLE)->where($map)->count();
        //计算pp
        $pp = ceil($count / $num) < $pp ? ceil($count / $num) : $pp;
        //查询数据
        // $list = Db::name(self::TABLE)->where($map)->order($order)->page($pp,$num)->field($field)->column("*","category_id");
        $list = Db::name(self::TABLE)->where($map)->order($order)->page($pp,$num)->field($field)->select();
        return [
            'list' => $list,
            'count' => $count,
            'pp' => $pp
        ];
    }


    /**
     * 类别添加
     *
     * @param array $param 类别信息
     * 
     * @return array
     */
    public static function add($param = [])
    {
        Db::startTrans();
        try{
            $param['category_status']      = 1;
            $param['category_create_time'] = date('Y-m-d H:i:s');
            $param['category_update_time'] = date('Y-m-d H:i:s');
            $category_id = Db::name(self::TABLE)->insertGetId($param);
            if (empty($category_id)) throw new Exception("数据库存储异常！");
            $param['category_id'] = $category_id;
            //redis添加
            $result = CateGoryCache::set($category_id,$param['category_type'],$param,0);
            if($result === false) throw new Exception("redis存储异常！");
            Db::commit();
            return [
                'category_id' => $category_id
            ];
        }catch(\Exception $e){
            Db::rollback();
            exception($e->getMessage());
        }
    }

    /**
     * 类别修改
     *
     * @param array $param 类别信息
     * 
     * @return array
     */
    public static function edit($param = [])
    {
        Db::startTrans();
        try{
            $category_id = $param['category_id'];
            //删除原类型缓存
            $info = Db::name(self::TABLE)->where("category_id",$category_id)->field("category_type")->find();
            $r = CateGoryCache::del($category_id,$info['category_type']);
            if($r === false) throw new Exception("redis删除原类型异常！");
            //更新数据和redis
            $param['category_update_time']    = date('Y-m-d H:i:s');
            $res = Db::name(self::TABLE)->where('category_id', $category_id)->update($param);
            if (empty($res)) throw new Exception("数据库更新异常！");
            $result = CateGoryCache::set($category_id,$param['category_type'],$param,0,true);
            if($result === false) throw new Exception("redis更新异常！");
            Db::commit();
            return [
                'msg' => '修改成功'
            ];
        }catch(\Exception $e){
            Db::rollback();
            exception($e->getMessage());
        }
    }

    /**
     * 类别删除
     *
     * @param array $param 类别信息
     * 
     * @return array
     */
    public static function dele($param)
    {
        Db::startTrans();
        try{
            $category_id = $param['category_id'];
            $type = $param['category_type'];
            $res = Db::name(self::TABLE)->delete($category_id);
            if(!$res) exception('数据库删除异常！');
            $result = CateGoryCache::del($category_id,$type);
            if($result === false) throw new Exception("redis删除异常！");
            Db::commit();
            return ['msg'=>'删除成功'];
        }catch(\Exception $e){
            Db::rollback();
            exception($e->getMessage());
        }
    }

    /**
     * 类别状态修改
     *
     * @param array $param 类别信息
     * 
     * @return array
     */
    public static function cateGoryStatusUpdate($param)
    {
        Db::startTrans();
        try{
            $category_id = $param['category_id'];
            $param['category_update_time'] = date('Y-m-d H:i:s');
            $res = Db::name(self::TABLE) ->where('category_id', $category_id)->update($param);
            if (empty($res)) throw new Exception("数据更新异常！");
            if($param['category_status'] == 2){
                //禁用则删除
                $result = CateGoryCache::del($category_id,$param['category_type']);
                if($result === false) throw new Exception("redis删除异常！");
            }else{
                //启动则存储
                $result = CateGoryCache::set($category_id,$param['category_type'],$param,0,true);
                if($result === false) throw new Exception("redis更新异常！");
            }
            Db::commit();
            return ['msg'=>'状态修改成功'];
        }catch(\Exception $e){
            Db::rollback();
            exception($e->getMessage());
        }
    }
}
